﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MINERP.DAL.CommonDAL;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using MINERP.DAL;

namespace MINERP.BLL.CustomerManage
{
    public class PrePrintBillBLL
    {
        public List<OrderProductUser> GetUnCountBill(DateTime inStartTime, DateTime inEndTime)
        {
            List<OrderProductUser> rtnList = new List<OrderProductUser>();
            StringBuilder sqlbuider = new StringBuilder();
            sqlbuider.Append(" select orderinfo.orderproductid as OrderProductId,orderinfo.orderproductname,shopname as ShopName,tb_orderbag.bagname as BagName,shop.Area as Area, ");
            sqlbuider.Append(" orderinfo.ctmname as CtmName,tb_orderbag.orderbagid BagCode,orderInfo.Priority,tb_Tech.techname as TechName,orderinfo.Width,orderinfo.Height,");
            sqlbuider.Append(" OrderTime,Tb_OrderBag.FetchTime,orderinfo.CompleteTime as CompleteTime,orderinfo.OrderPath,isCount,orderinfo.Area as photoArea,orderinfo.Remark Remark,orderinfo.status as status,shop.shopid as shopid,billid=0");
            sqlbuider.Append(" from orderinfo,tb_orderbag,shop,WorkOrderFlowList,tb_Tech");
            sqlbuider.Append(" where shop.shopid=tb_orderbag.shopid ");
            sqlbuider.Append(" and tb_orderbag.OrderBagId=orderinfo.OrderBagId");
            sqlbuider.Append(" and orderinfo.status=1 and orderinfo.producttype=4 ");
            sqlbuider.Append(" and orderinfo.orderproductid=WorkOrderFlowList.orderproductid");
            sqlbuider.Append(" and WorkOrderFlowList.status=1");
            sqlbuider.Append(" and WorkOrderFlowList.techid=tb_Tech.techid");
            sqlbuider.Append(" and (orderinfo.iscount IS NULL or orderinfo.iscount=0)");
            sqlbuider.Append(" and tb_orderbag.OrderTime>'" + inStartTime.ToString("yyyy-MM-dd") + "' and tb_orderbag.OrderTime<'" + inEndTime.ToString("yyyy-MM-dd") + "'");
            DataTable table = CommOperDB.ExceSQLDataSet(sqlbuider.ToString()).Tables[0];

            return OrderInfoChangeDT(table);
        }
        public List<OrderProductUser> GetCountBill(DateTime inStartTime, DateTime inEndTime)
        {
            List<OrderProductUser> rtnList = new List<OrderProductUser>();
            StringBuilder sqlbuider = new StringBuilder();
            sqlbuider.Append(" select orderinfo.orderproductid as OrderProductId,orderinfo.orderproductname,shopname as ShopName,tb_orderbag.bagname as BagName,shop.Area as Area, ");
            sqlbuider.Append(" orderinfo.ctmname as CtmName,tb_orderbag.orderbagid BagCode,orderInfo.Priority,tb_Tech.techname as TechName,orderinfo.Width,orderinfo.Height,");
            sqlbuider.Append(" Tb_OrderBag.OrderTime,Tb_OrderBag.FetchTime,orderinfo.CompleteTime as CompleteTime,orderinfo.OrderPath,isCount,orderinfo.Area as photoArea,Bill_Detail.Billid as billid,orderinfo.Remark as Remark,orderinfo.status as status,tb_orderbag.shopid as shopid");
            sqlbuider.Append(" from orderinfo,tb_orderbag,shop,WorkOrderFlowList,tb_Tech,Bill_Detail");
            sqlbuider.Append(" where shop.shopid=tb_orderbag.shopid ");
            sqlbuider.Append(" and tb_orderbag.OrderBagId=orderinfo.OrderBagId");
            sqlbuider.Append(" and Bill_Detail.OrderInfoCode=orderinfo.OrderProductCode");
            sqlbuider.Append(" and orderinfo.status=1 ");
            sqlbuider.Append(" and orderinfo.orderproductid=WorkOrderFlowList.orderproductid");
            sqlbuider.Append(" and WorkOrderFlowList.status=1");
            sqlbuider.Append(" and orderinfo.iscount=1");
            sqlbuider.Append(" and WorkOrderFlowList.techid=tb_Tech.techid");
            sqlbuider.Append(" and tb_orderbag.OrderTime>'" + inStartTime.ToString("yyyy-MM-dd") + "' and tb_orderbag.OrderTime<'" + inEndTime.ToString("yyyy-MM-dd") + "'");
            DataTable table = CommOperDB.ExceSQLDataSet(sqlbuider.ToString()).Tables[0];

            return OrderInfoChangeDT(table); ;
        }
        private List<OrderProductUser> OrderInfoChangeDT(DataTable dt)
        {
            try
            {
                List<OrderProductUser> products = new List<OrderProductUser>();
                foreach (DataRow info in dt.Rows)
                {
                    OrderProductUser product = new OrderProductUser();
                    product.ShopName = info["ShopName"].ToString();
                    product.Area = info["Area"].ToString();
                    //if (info["BillCreateTime"] != DBNull.Value)
                    //    product.BillCreateTime = Convert.ToDateTime(info["BillCreateTime"]).ToString("yyyy-MM-dd HH:mm");
                    product.CompletedTime = Convert.ToDateTime(info["CompleteTime"]);
                    product.CtmName = info["CtmName"].ToString();
                    product.CurrentTech = info["TechName"].ToString();//获取产品当前流程

                    product.Height = Convert.ToDouble(info["Height"]);
                    product.Width = Convert.ToDouble(info["Width"]);
                    product.OrderCode = info["BagCode"].ToString();
                    product.OrderName = info["BagName"].ToString();
                    product.OrderTime = Convert.ToDateTime(info["OrderTime"]);
                    product.FetchTime = Convert.ToDateTime(info["FetchTime"]);
                    //product.OrderProductCode = info["OrderProductCode"].ToString();
                    product.OrderProductId = Convert.ToInt32(info["OrderProductId"]);
                    product.OrderProductName = info["OrderProductName"].ToString();
                    product.OrderProductPath = info["OrderPath"].ToString();
                    product.Remark = info["Remark"].ToString();
                    product.IsSelect = false;
                    product.Status = Convert.ToInt16(info["status"]);
                    product.ShopID = Convert.ToInt32(info["shopid"]);
                    if (info["BillID"] != DBNull.Value)
                    {
                        product.BillID = Convert.ToInt32(info["BillID"]);
                    }
                    else
                    {
                        product.BillID = 0;
                    }

                    //if (info["photoNum"] != DBNull.Value)
                    //    product.PhotoNum = Convert.ToInt32(info["photoNum"]);
                    //else
                    //    product.PhotoNum = 0;
                    if (info["photoArea"] != DBNull.Value)
                        product.photoArea = Math.Round(Convert.ToDouble(info["photoArea"]), 2);
                    else
                        product.photoArea = 0;

                    if (info["Priority"] == DBNull.Value)
                        product.OrderProductPriority = 0;
                    else
                        product.OrderProductPriority = Convert.ToInt16(info["Priority"]);
                    product.StatusStr = GetInfoStatusStr(product.Status);
                    if (info["iscount"] != DBNull.Value)
                    {
                        int iscount = Convert.ToInt32(info["iscount"]);
                        if (iscount == 0)
                        {
                            product.IsCount = false;

                        }
                        else if (iscount == 1)
                        {
                            product.IsCount = true;
                        }
                    }
                    else
                    {
                        product.IsCount = false;
                    }
                    products.Add(product);
                }
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 产品的中文状态
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetInfoStatusStr(int status)
        {
            string statusStr = "";
            OrderInfoStatus os = (OrderInfoStatus)status;
            switch (os)
            {
                case OrderInfoStatus.WaitCheck:
                    statusStr = "等待审核"; break;
                case OrderInfoStatus.Doing:
                    statusStr = "正在生产中"; break;
                case OrderInfoStatus.Error:
                    statusStr = "发生错误"; break;
                case OrderInfoStatus.FenPianCompleted:
                    statusStr = "分片完成"; break;
                case OrderInfoStatus.OutProcess:
                    statusStr = "委外加工中"; break;
                case OrderInfoStatus.OverOrder:
                    statusStr = "已结单"; break;
                case OrderInfoStatus.Received:
                    statusStr = "已收件"; break;
                case OrderInfoStatus.Stop:
                    statusStr = "停止生产"; break;
                case OrderInfoStatus.Completed:
                    statusStr = "完成"; break;
                case OrderInfoStatus.NoCheckCount:
                case OrderInfoStatus.WaitPay:
                    statusStr = "余额不足"; break;
                case OrderInfoStatus.WaitPhotoMove:
                case OrderInfoStatus.WaitPayAndWaitMovePhoto:
                    statusStr = "移动照片"; break;
                case OrderInfoStatus.Deleted:
                    statusStr = "删除"; break;
                case OrderInfoStatus.AutoOrderWait:
                    statusStr = "远程开单等待审核"; break;
                default: statusStr = "未知状态"; break;
            }
            return statusStr;
        }

        public List<SHOP_Bill_Info> OrganizationBillDataList(int OrderBagID)
        {
            List<SHOP_Bill_Info> rtnList = new List<SHOP_Bill_Info>();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                {
                    dataBase.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                try
                {
                    Tb_OrderBag orderbag = dataBase.Tb_OrderBag.FirstOrDefault(b => b.OrderBagId == OrderBagID);
                    if (orderbag == null)
                    {

                        return rtnList;
                    }
                    orderbag.ShopReference.Load();
                    orderbag.orderInfo.Load();
                    Shop curShop = orderbag.Shop;
                    List<orderInfo> orderList = orderbag.orderInfo.Where(o => o.isCount == 0 || o.isCount == null).ToList();
                    if (orderList.Count == 0)
                    {

                        return rtnList;
                    }


                    foreach (orderInfo oi in orderList)
                    {
                        SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                        SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用

                        List<int> DonedOrderProudctId = new List<int>(orderList.Count);//能够正常结帐单的产品ID
                        //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                        //初始信息
                        double Bill_Price = 0;
                        bool hasForcibePrint = true;
                        sb.NeedDeliver = 1;                                 //是否需要配送   
                        sb.Status = (int)ShopBillStatus.UnCheckOut;

                        sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                        sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                        int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样

                        sbinfo.List_Detail = new List<Bill_Detail_Info>();



                        #region 得到商户的帐单的顺序号

                        List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == curShop.ShopId).ToList();
                        if (listShopBill.Count <= 0)
                        {
                            sb.BillOrderCode = 1;
                        }
                        else
                        {
                            sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                        }


                        //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                        sbinfo.BillOrderCode = sb.BillOrderCode;




                        #endregion


                        sbinfo.BillOrderCode = sb.BillOrderCode;


                        decimal orderInfoPrice = 0;//此产品的真实价格

                        //orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                        oi.photoInfo.Load();

                        #region 加载数据库
                        if (!oi.Tb_ProductReference.IsLoaded)
                        {
                            oi.Tb_ProductReference.Load();
                        }
                        if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                        {
                            oi.Tb_Product.tb_CostTypeReference.Load();
                        }
                        if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        {
                            oi.Tb_Product.Tb_PorductCategoryReference.Load();
                        }
                        if (!curShop.Shop_Product_Price.IsLoaded)
                        {
                            curShop.Shop_Product_Price.Load();
                        }
                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }
                        if (!oi.Tb_OrderBagReference.IsLoaded)
                        {
                            oi.Tb_OrderBagReference.Load();
                        }
                        if (!oi.WorkOrderFlowList.IsLoaded)
                        {
                            oi.WorkOrderFlowList.Load();
                            oi.WorkOrderFlowList.ToList().ForEach(w => w.tb_TechReference.Load());
                        }
                        if (oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == 4) != null)
                        {
                            continue;
                        }
                        string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                        #endregion

                        Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                        Bill_Detail_Id++;
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                        orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                        #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                        #region //对帐户金额的操作
                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                            case 5://先结
                                #region


                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)orderInfoPrice)
                                {
                                    //如果余额不足，就判断是否有权限可打印此帐单
                                    if (hasForcibePrint)//可以强打
                                    {
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        curShop.Balance -= (decimal)orderInfoPrice;
                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        dataBase.AddToShopBlanceCrushRecord(br);
                                    }
                                    else
                                    {
                                        oi.status = (int)OrderInfoStatus.WaitPay;
                                        curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                        DonedOrderProudctId.Remove(oi.OrderProductId);
                                    }
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)orderInfoPrice;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户
                            case 6://代收款
                                #region
                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)orderInfoPrice;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }

                        #endregion
                        sb.Bill_Detail.Add(bd);

                        dbinfo.BillDetailId = Bill_Detail_Id;
                        sbinfo.List_Detail.Add(dbinfo);
                        Bill_Detail_Id++;
                        Bill_Price += (double)orderInfoPrice;
                        oi.isCount = (int)orderinfoPerBill.Printed;//0为
                        dataBase.SaveChanges();
                        #endregion


                        //return sbinfo;

                        //记录帐单信息          
                        sb.Shop = curShop;
                        sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                        sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                        //sbinfo.BillCount = Bill_Price;
                        sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                        {
                            if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                            {
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                            }
                            else
                            {
                                sb.Status = (int)ShopBillStatus.CheckedOut;
                            }
                            sb.ShopBalance = curShop.Balance ?? 0;
                            dataBase.AddToSHOP_Bill(sb);

                            dataBase.SaveChanges();

                        }
                        else
                        {
                            sbinfo = null;
                            sb = null;

                        }
                        if (sbinfo != null)
                        {
                            sbinfo.BillId = sb.BillId;
                            sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                        }
                        rtnList.Add(sbinfo);
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {

                    tran.Rollback();
                    rtnList = new List<SHOP_Bill_Info>();
                }



                return rtnList;
            }
        }
        /// <summary>
        /// 将选择的同一家商户的产品打印在不同的账单上
        /// </summary>
        /// <param name="inListOrderid"></param>
        /// <param name="inShopID"></param>
        /// <returns></returns>
        public List<SHOP_Bill_Info> OrganizationBillDataListFromOrderList(List<int> inListOrderid, int inShopID)
        {
            List<SHOP_Bill_Info> rtnList = new List<SHOP_Bill_Info>();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                {
                    dataBase.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                try
                {


                    Shop curShop = dataBase.Shop.FirstOrDefault(p => p.ShopId == inShopID);
                    List<orderInfo> orderList = new List<orderInfo>();
                    foreach (int orderid in inListOrderid)
                    {
                        orderInfo orderIn = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == orderid);

                        if (orderIn != null && orderIn.isCount != 1)
                        {
                            orderList.Add(orderIn);
                        }
                    }

                    if (orderList.Count == 0)
                    {

                        return rtnList;
                    }








                    foreach (orderInfo oi in orderList)
                    {

                        SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                        SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用

                        List<int> DonedOrderProudctId = new List<int>(orderList.Count);//能够正常结帐单的产品ID
                        //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                        //初始信息
                        double Bill_Price = 0;
                        bool hasForcibePrint = true;
                        sb.NeedDeliver = 1;                                 //是否需要配送   
                        sb.Status = (int)ShopBillStatus.UnCheckOut;

                        sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                        sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                        int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样

                        sbinfo.List_Detail = new List<Bill_Detail_Info>();


                        decimal orderInfoPrice = 0;//此产品的真实价格

                        //orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                        #region 得到商户的帐单的顺序号

                        List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == curShop.ShopId).ToList();
                        if (listShopBill.Count <= 0)
                        {
                            sb.BillOrderCode = 1;
                        }
                        else
                        {
                            sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                        }
                        sbinfo.BillOrderCode = sb.BillOrderCode;

                        //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                        sbinfo.BillOrderCode = sb.BillOrderCode;




                        #endregion
                        oi.photoInfo.Load();

                        #region 加载数据库
                        if (!oi.Tb_ProductReference.IsLoaded)
                        {
                            oi.Tb_ProductReference.Load();
                        }
                        if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                        {
                            oi.Tb_Product.tb_CostTypeReference.Load();
                        }
                        if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        {
                            oi.Tb_Product.Tb_PorductCategoryReference.Load();
                        }
                        if (!curShop.Shop_Product_Price.IsLoaded)
                        {
                            curShop.Shop_Product_Price.Load();
                        }
                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }
                        if (!oi.Tb_OrderBagReference.IsLoaded)
                        {
                            oi.Tb_OrderBagReference.Load();
                        }
                        if (!oi.WorkOrderFlowList.IsLoaded)
                        {
                            oi.WorkOrderFlowList.Load();
                            oi.WorkOrderFlowList.ToList().ForEach(w => w.tb_TechReference.Load());
                        }
                        if (oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == 4) != null)
                        {
                            continue;
                        }
                        string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                        #endregion

                        Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                        Bill_Detail_Id++;
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                        orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                        #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                        #region //对帐户金额的操作
                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                            case 5://先结
                                #region


                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)orderInfoPrice)
                                {
                                    //如果余额不足，就判断是否有权限可打印此帐单
                                    if (hasForcibePrint)//可以强打
                                    {
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        curShop.Balance -= (decimal)orderInfoPrice;
                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        dataBase.AddToShopBlanceCrushRecord(br);
                                    }
                                    else
                                    {
                                        oi.status = (int)OrderInfoStatus.WaitPay;
                                        curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                        DonedOrderProudctId.Remove(oi.OrderProductId);
                                    }
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)orderInfoPrice;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户
                            case 6://代收款
                                #region
                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)orderInfoPrice;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }

                        #endregion
                        sb.Bill_Detail.Add(bd);

                        dbinfo.BillDetailId = Bill_Detail_Id;
                        sbinfo.List_Detail.Add(dbinfo);
                        Bill_Detail_Id++;
                        Bill_Price += (double)orderInfoPrice;
                        oi.isCount = (int)orderinfoPerBill.Printed;//0为
                        dataBase.SaveChanges();
                        #endregion

                        #region//对产品流程进行操作
                        oi.WorkOrderFlowList.Load();
                        foreach (WorkOrderFlowList wof in oi.WorkOrderFlowList)
                        {
                            wof.tb_TechReference.Load();
                        }
                        //检查分片节点
                        int fenpianTech = (int)TechType.FenPian;
                        WorkOrderFlowList curWOF = oi.WorkOrderFlowList.FirstOrDefault(wf => wf.tb_Tech.TechType == fenpianTech);
                        if (curWOF != null)
                        {
                            if (curWOF.Status == 4)//已经分片完成了
                            {
                                //分片完成将流程结束
                                foreach (WorkOrderFlowList wfl in oi.WorkOrderFlowList.Where(p => p.Status == 0 || p.Status == 1))
                                {
                                    wfl.Status = 4;
                                    wfl.CompletedTime = DateTime.Now;
                                    wfl.UserId = dataBase.users.FirstOrDefault().userID;
                                }
                                //修改产品状态和订单状态
                                oi.status = (int)OrderInfoStatus.Completed;
                                int OComplete = (int)OrderInfoStatus.Completed;
                                oi.status = (int)OrderInfoStatus.Completed;
                                oi.Tb_OrderBag.orderInfo.Load();
                                List<orderInfo> listOrderInBag = oi.Tb_OrderBag.orderInfo.ToList();
                                if (oi.Tb_OrderBag.orderInfo.Count == oi.Tb_OrderBag.orderInfo.Where(o => o.status == OComplete).Count())
                                {
                                    oi.Tb_OrderBag.Status = (int)OrderBagStatus.Completed;
                                }
                            }


                        }

                        #endregion
                        //记录帐单信息          
                        sb.Shop = curShop;
                        sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                        sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                        //sbinfo.BillCount = Bill_Price;
                        sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                        {
                            if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                            {
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                            }
                            else
                            {
                                sb.Status = (int)ShopBillStatus.CheckedOut;
                            }
                            sb.ShopBalance = curShop.Balance ?? 0;
                            dataBase.AddToSHOP_Bill(sb);

                            dataBase.SaveChanges();

                        }
                        else
                        {
                            sbinfo = null;
                            sb = null;

                        }
                        if (sbinfo != null)
                        {
                            sbinfo.BillId = sb.BillId;
                            sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                        }
                        rtnList.Add(sbinfo);
                    }
                    //return sbinfo;



                    tran.Commit();
                }
                catch (Exception ex)
                {

                    tran.Rollback();
                    rtnList = new List<SHOP_Bill_Info>();
                }



                return rtnList;
            }
        }

        /// 将Bill_Detail转换为要打印的信息
        /// </summary>
        /// <param name="bd"></param>
        /// <param name="curShop"></param>
        /// <param name="bdInfo"></param>
        private void ConvertOrderDetailaToViewModel(Bill_Detail bd, Shop curShop, Bill_Detail_Info bdInfo)
        {
            foreach (var bdd in bd.Bill_Detail_Detail.ToList())
            {
                bdInfo.ListDetail_Detail.Add(new Bill_Detail_Detail_Info()
                {
                    Area = bdd.Area,
                    Count = bdd.Count,
                    DetailName = bdd.DetailName,
                    Num = bdd.Num,
                    Spec = bdd.Spec,
                    Type = bdd.Type ?? 0,
                    UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0,
                    Bill_Detail_DetailId = bdInfo.BillDetailId,
                    DetailRemark = bdd.DetailRemark
                });
            }
        }
        /// <summary>
        /// 讲选择同一家商户的产品打印在一张账单上
        /// </summary>
        /// <param name="inListOrderid"></param>
        /// <param name="inShopID"></param>
        /// <returns></returns>
        public SHOP_Bill_Info OrganizationBillDataFromOrderList(List<int> inListOrderid, int inShopID)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                {
                    dataBase.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
                sbinfo.Result = 0;

                Shop curShop = dataBase.Shop.FirstOrDefault(s => s.ShopId == inShopID);
                List<orderInfo> orderList = new List<orderInfo>();
                inListOrderid = inListOrderid.Distinct().ToList();
                foreach (int orderproductid in inListOrderid)
                {
                    orderInfo oinfo = dataBase.orderInfo.FirstOrDefault(or => or.OrderProductId == orderproductid);
                    if (oinfo == null && oinfo.isCount == 1)
                    { }
                    else
                    {
                        orderList.Add(oinfo);
                    }
                }

                List<int> DonedOrderProudctId = new List<int>(orderList.Count);//能够正常结帐单的产品ID
                //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                //初始信息
                double Bill_Price = 0;
                bool hasForcibePrint = true;
                sb.NeedDeliver = 1;                                 //是否需要配送   
                sb.Status = (int)ShopBillStatus.UnCheckOut;

                sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样

                sbinfo.List_Detail = new List<Bill_Detail_Info>();



                #region 得到商户的帐单的顺序号

                List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == curShop.ShopId).ToList();
                if (listShopBill.Count <= 0)
                {
                    sb.BillOrderCode = 1;
                }
                else
                {
                    sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                }


                //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                sbinfo.BillOrderCode = sb.BillOrderCode;




                #endregion


                sbinfo.BillOrderCode = sb.BillOrderCode;
                foreach (orderInfo oi in orderList)
                {



                    decimal orderInfoPrice = 0;//此产品的真实价格

                    //orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                    oi.photoInfo.Load();

                    #region 加载数据库
                    if (!oi.Tb_ProductReference.IsLoaded)
                    {
                        oi.Tb_ProductReference.Load();
                    }
                    if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                    {
                        oi.Tb_Product.tb_CostTypeReference.Load();
                    }
                    if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                    {
                        oi.Tb_Product.Tb_PorductCategoryReference.Load();
                    }
                    if (!curShop.Shop_Product_Price.IsLoaded)
                    {
                        curShop.Shop_Product_Price.Load();
                    }
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    if (!oi.WorkOrderFlowList.IsLoaded)
                    {
                        oi.WorkOrderFlowList.Load();
                        oi.WorkOrderFlowList.ToList().ForEach(w => w.tb_TechReference.Load());
                    }
                    if (oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == 4) != null)
                    {
                        continue;
                    }
                    string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                    #endregion

                    Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                    Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                    Bill_Detail_Id++;
                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                    orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                    ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                    #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                    #region //对帐户金额的操作
                    ShopBlanceCrushRecord br;
                    switch (curShop.CheckOutType)
                    {
                        case 0://预付款用户
                        case 2://现结用户
                        case 5://先结
                            #region


                            curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                            if (curShop.OrderBalance < 0)
                            {
                                curShop.OrderBalance = 0;
                            }


                            if (curShop.Balance < (decimal)orderInfoPrice)
                            {
                                //如果余额不足，就判断是否有权限可打印此帐单
                                if (hasForcibePrint)//可以强打
                                {
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    curShop.Balance -= (decimal)orderInfoPrice;
                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }
                                else
                                {
                                    oi.status = (int)OrderInfoStatus.WaitPay;
                                    curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                    DonedOrderProudctId.Remove(oi.OrderProductId);
                                }
                            }
                            else
                            {

                                bd.IsCheckOut = true;
                                curShop.Balance -= (decimal)orderInfoPrice;

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                            }

                            //检查是否需要报警
                            if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                            {
                                BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                            }
                            #endregion
                            break;
                        case 1://信用额度用户
                        case 3://结帐日用户
                        case 4://结单日与信用额度用户
                        case 6://代收款
                            #region
                            curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                            if (curShop.OrderBalance < 0)
                            {
                                curShop.OrderBalance = 0;
                            }
                            curShop.Balance -= (decimal)orderInfoPrice;

                            if (curShop.CheckOutType == 1)//信用额度用户
                            {
                                if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                }
                            }
                            else
                            {
                                int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                if (days > 0 && days < curShop.AlarmDays)
                                {
                                    BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                            }

                            //向商户帐户记录表添加记录
                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                            dataBase.AddToShopBlanceCrushRecord(br);
                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                            #endregion
                            break;
                        default:
                            break;
                    }

                    #endregion
                    sb.Bill_Detail.Add(bd);

                    dbinfo.BillDetailId = Bill_Detail_Id;
                    sbinfo.List_Detail.Add(dbinfo);
                    Bill_Detail_Id++;
                    Bill_Price += (double)orderInfoPrice;
                    oi.isCount = (int)orderinfoPerBill.Printed;//0为

                    //对产品流程进行操作
                    oi.WorkOrderFlowList.Load();
                    foreach (WorkOrderFlowList wof in oi.WorkOrderFlowList)
                    {
                        wof.tb_TechReference.Load();
                    }

                    dataBase.SaveChanges();
                    #endregion
                    #region//对流程和生成进行操作
                    //检查分片节点
                    int fenpianTech = (int)TechType.FenPian;
                    WorkOrderFlowList curWOF = oi.WorkOrderFlowList.FirstOrDefault(wf => wf.tb_Tech.TechType == fenpianTech);
                    if (curWOF != null)
                    {
                        if (curWOF.Status == 4)//已经分片完成了
                        {
                            //如果分片完成就吧剩下的流程结束掉
                            foreach (WorkOrderFlowList wfl in oi.WorkOrderFlowList.Where(p => p.Status == 0 || p.Status == 1))
                            {
                                wfl.Status = 4;
                                wfl.CompletedTime = DateTime.Now;
                                wfl.UserId = dataBase.users.FirstOrDefault().userID;
                            }
                            //修改产状态及其订单状态
                            int OComplete = (int)OrderInfoStatus.Completed;
                            oi.status = (int)OrderInfoStatus.Completed;
                            oi.Tb_OrderBag.orderInfo.Load();
                            List<orderInfo> listOrderInBag = oi.Tb_OrderBag.orderInfo.ToList();
                            if (oi.Tb_OrderBag.orderInfo.Count == oi.Tb_OrderBag.orderInfo.Where(o => o.status == OComplete).Count())
                            {
                                oi.Tb_OrderBag.Status = (int)OrderBagStatus.Completed;
                            }
                        }


                    }

                    #endregion

                    //return sbinfo;


                }

                //记录帐单信息          
                sb.Shop = curShop;
                sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                //sbinfo.BillCount = Bill_Price;
                sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                {
                    if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                    {
                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                    }
                    else
                    {
                        sb.Status = (int)ShopBillStatus.CheckedOut;
                    }
                    sb.ShopBalance = curShop.Balance ?? 0;
                    dataBase.AddToSHOP_Bill(sb);

                    dataBase.SaveChanges();
                    tran.Commit();
                }
                else
                {
                    sbinfo = null;
                    sb = null;
                    tran.Rollback();
                }
                if (sbinfo != null)
                {
                    sbinfo.BillId = sb.BillId;
                    sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                }
                return sbinfo;
            }
        }
        /// <summary>
        /// 检查产品是否符合前置打单条件
        /// </summary>
        /// <param name="inListOrderid"></param>
        /// <returns></returns>
        public List<int> CheckOrder(List<int> inListOrderid)
        {
            int fenPian = (int)TechType.FenPian;
            int weiwai = (int)TechType.OutProduct;
            List<int> Oklist = new List<int>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (int orderid in inListOrderid)
                {
                    orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderid);
                    if (oi != null && oi.isCount != 1)
                    {
                        oi.WorkOrderFlowList.Load();
                        oi.WorkOrderFlowList.ToList().ForEach(w => w.tb_TechReference.Load());
                        WorkOrderFlowList fenpianW = oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == fenPian);
                        if (fenpianW != null)
                        {
                            WorkOrderFlowList weiwaiW = oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == weiwai);
                            if (weiwaiW == null)
                            {
                                Oklist.Add(orderid);
                            }

                        }
                    }
                }
            }

            return Oklist;
        }


        /// <summary>
        /// 根据ID得到这些影楼下的所有帐单
        /// </summary>
        /// <param name="selectedShopList"></param>
        /// <param name="dateTime"></param>
        /// <param name="dateTime_3"></param>
        /// <returns></returns>
        public SHOP_Bill_Info GetBillByid(int inBillid)
        {
            SHOP_Bill_Info rtnBill = new SHOP_Bill_Info(); ;

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {

                int delStatus = (int)ShopBillStatus.Delete;
                int uncheckStatus = (int)ShopBillStatus.UnCheckOut;

                SHOP_Bill sb = db.SHOP_Bill.FirstOrDefault(s => s.BillId == inBillid);
                if (sb == null)
                {
                    rtnBill = null;
                }
                else
                {

                    //一个个地帐单
                    if (!sb.ShopReference.IsLoaded)
                    {
                        sb.ShopReference.Load();
                    }
                    SHOP_Bill_Info sbinfo = new SHOP_Bill_Info()
                    {
                        BillCount = Convert.ToDouble(sb.TotalPrice ?? 0),
                        BillId = sb.BillId,
                        BillOrderCode = sb.BillOrderCode,
                        CreateTime = sb.CreateTime,
                        List_Detail = new List<Bill_Detail_Info>(),
                        ShopBalance = Convert.ToDouble(sb.ShopBalance),
                        Status = sb.Status,

                        // IsAssignByCustom=sb.Shop.IsAssignByCustom,
                        NeedPrice = (bool)sb.Shop.IsNeedPrintUPrice
                    };
                    sbinfo.List_Detail = new List<Bill_Detail_Info>();
                    sbinfo.Shop = new Shop_Info()
                    {
                        Address = sb.Shop.address,
                        Balance = sb.Shop.Balance ?? 0,
                        Remark = sb.Shop.Remark,
                        Area = sb.Shop.Area,
                        CheckOutType = sb.Shop.CheckOutType,
                        CreditLevel = sb.Shop.CreditLevel ?? 0,
                        Tel1 = sb.Shop.Tel1,
                        Tel2 = sb.Shop.Tel2,
                        CreditLimit = sb.Shop.CreditLimit ?? 0,
                        EmailAddr = sb.Shop.EmailAddr,
                        IsNeedPrintUPrice = sb.Shop.IsNeedPrintUPrice ?? false,
                        QQ = sb.Shop.QQ,
                        MSN = sb.Shop.MSN,
                        Priority = sb.Shop.Priority ?? 0,
                        ShopName = sb.Shop.shopName,
                        ShopId = sb.Shop.ShopId,
                        Status = sb.Shop.Status ?? 0,
                        Salesman = sb.Shop.Salesman,
                        OrderBalance = sb.Shop.OrderBalance ?? 0
                    };


                    if (!sb.Bill_Detail.IsLoaded)
                    {
                        sb.Bill_Detail.Load();
                    }
                    foreach (var bd in sb.Bill_Detail.ToList())
                    {
                        //产品
                        Bill_Detail_Info bdetailInfo = new Bill_Detail_Info()
                        {
                            BillDetailId = bd.BillDetailId,
                            CtmName = bd.CtmName,
                            OrderInfoCode = bd.OrderInfoCode,
                            OrderProductName = bd.OrderProductName,
                            Remark = bd.OiRemark,
                            ListDetail_Detail = new List<Bill_Detail_Detail_Info>()
                        };


                        //加明细
                        if (!bd.Bill_Detail_Detail.IsLoaded)
                        {
                            bd.Bill_Detail_Detail.Load();
                        }
                        foreach (var bdd in bd.Bill_Detail_Detail.ToList())
                        {
                            bdetailInfo.ListDetail_Detail.Add(new Bill_Detail_Detail_Info()
                            {
                                Area = bdd.Area,
                                Count = bdd.Count,
                                DetailName = bdd.DetailName,
                                Num = bdd.Num,
                                Spec = bdd.Spec,
                                Type = bdd.Type ?? 0,
                                UnitPrice = bdd.UnitPrice,
                                DetailRemark = bdd.DetailRemark
                            });
                        }
                        sbinfo.List_Detail.Add(bdetailInfo);
                    }

                    rtnBill = sbinfo;

                }
            }

            return rtnBill;
        }

        /// <summary>
        /// 获取所有商户列表
        /// </summary>
        /// <returns></returns>
        public List<Shop_Info> GetShopList()
        { 
            List<Shop_Info>returnList=new List<Shop_Info>();
            using(newSampleYPDBEntities db =new newSampleYPDBEntities())
            {
                List<Shop> lisShop=db.Shop.Where(s=>s.Status==1).ToList();
                foreach(Shop s in lisShop)
                {
                    Shop_Info si =new Shop_Info();
                    si.ShopId=s.ShopId;
                    si.ShopName=s.shopName;
                    si.MnemonicCode=s.mnemonicCode;
                    returnList.Add(si);
                }
            }
            return  returnList;
        }


        public SHOP_Bill_Info SetShippingFee(string inDetailName, int inShopID, decimal inUnitPrice, decimal inNum, int inOperUserID)
        {
            SHOP_Bill_Info rtnInfo = new SHOP_Bill_Info();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {

                //System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
                sbinfo.Result = 0;

                Shop curShop = dataBase.Shop.FirstOrDefault(s => s.ShopId == inShopID);



                //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                //初始信息
                double Bill_Price = 0;
                bool hasForcibePrint = true;
                sb.NeedDeliver = 1;                                 //是否需要配送   
                sb.Status = (int)ShopBillStatus.UnCheckOut;

                sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样
                sb.Shop = curShop;
              
                users user = dataBase.users.FirstOrDefault(u => u.userID == inOperUserID);




                List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == curShop.ShopId).ToList();
                if (listShopBill.Count <= 0)
                {
                    sb.BillOrderCode = 1;
                }
                else
                {
                    sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                }
                sb.CreateTime = DateTime.Now;
               

                //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                sbinfo.BillOrderCode = sb.BillOrderCode;

                Bill_Detail bdetial = new Bill_Detail();
                bdetial.CtmName = inDetailName;
                bdetial.OiRemark = inDetailName;
                bdetial.OrderInfoCode = "000000000";
                bdetial.OrderProductName = inDetailName;
                bdetial.OrderTime = DateTime.Now;
                // bdetial.Bill_Detail_Detail = new System.Data.Objects.DataClasses.EntityCollection<Bill_Detail_Detail>();
                Bill_Detail_Detail bdd = new Bill_Detail_Detail();
                bdd.Area = 0;
                bdd.Count = (double)(inUnitPrice * inNum);
                bdd.DetailName = inDetailName;
                bdd.DetailRemark = inDetailName;
                bdd.Num = (int)inNum;
                bdd.Spec = "1x1";
                bdd.UnitPrice = (double)inUnitPrice;
                bdd.Type = 0;
                bdetial.Bill_Detail_Detail.Add(bdd);
                sb.Bill_Detail.Add(bdetial);
                decimal orderInfoPrice = (decimal)bdd.Count;
            
                #region //对帐户金额的操作
                ShopBlanceCrushRecord br;
                switch (curShop.CheckOutType)
                {
                    case 0://预付款用户
                    case 2://现结用户
                    case 5://先结
                        #region



                        if (curShop.OrderBalance < 0)
                        {
                            curShop.OrderBalance = 0;
                        }




                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                        curShop.Balance -= (decimal)orderInfoPrice;
                        //向商户帐户记录表添加记录
                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = user.UserName, Overage = (decimal)curShop.Balance, Remark = "运费：" + " ", Operation = (int)CountOperationType.DiChong };
                        dataBase.AddToShopBlanceCrushRecord(br);

                        //检查是否需要报警
                        if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                        {
                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                        }
                        #endregion
                        break;
                    case 1://信用额度用户
                    case 3://结帐日用户
                    case 4://结单日与信用额度用户
                    case 6://代收款
                        #region
                       
                        if (curShop.OrderBalance < 0)
                        {
                            curShop.OrderBalance = 0;
                        }
                        curShop.Balance -= (decimal)orderInfoPrice;

                        if (curShop.CheckOutType == 1)//信用额度用户
                        {
                            if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                            {
                                BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                            }
                        }
                        else
                        {
                            int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                            if (days > 0 && days < curShop.AlarmDays)
                            {
                                BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "运费金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                            }
                        }

                        //向商户帐户记录表添加记录
                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = user.UserName, Overage = (decimal)curShop.Balance, Remark = "运费 ", Operation = (int)CountOperationType.DiChong };
                        dataBase.AddToShopBlanceCrushRecord(br);
                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                        #endregion
                        break;
                    default:
                        break;
                }

                #endregion
                sb.TotalPrice = (decimal)bdd.Count; ;

               
                sb.Shop = curShop;
                sb.ShopBalance = (decimal)curShop.Balance;
                sb.Status = (int)ShopBillStatus.UnCheckOut;
                dataBase.SaveChanges();
                rtnInfo = GetBillByid(sb.BillId);



            }
            return rtnInfo;
        }


    }
    public class OrderProductUser
    {
        public int OrderProductId { get; set; }
        public string Area { get; set; }
        public string ShopName { get; set; }
        public string OrderProductCode { get; set; }
        public string OrderProductName { get; set; }
        public int OrderProductPriority { get; set; }
        public string OutShopName { get; set; }
        public DateTime OutShopStartProductTime { get; set; }       //委外商接收产品时间
        public string OrderCode { get; set; }
        public string OrderName { get; set; }
        public DateTime OrderTime { get; set; }
        public DateTime FetchTime { get; set; }                     //
        public string CtmName { get; set; }
        public DateTime CompletedTime { get; set; }             //?完成时间
        //public string BillCreateTime { get; set; }              //账单打印时间
        public int Status { get; set; }
        public string StatusStr { get; set; }
        public string OrderProductPath { get; set; }
        public double Width { get; set; }
        public double Height { get; set; }
        public string CurrentTech { get; set; }
        public DateTime TechTime { get; set; }                  //节点时间？(到底需要什么时间)
        public string Remark { get; set; }
        public int PhotoNum { get; set; }     //产品照片总张数
        public double photoArea { get; set; }//产品照片总面积
        public bool IsSelect { get; set; }//是否选择
        public bool IsCount { get; set; }//是否打印过账单
        public int ShopID { get; set; }
        public int BillID { get; set; }
    }
}
